<?php

class Graph_model extends Model {


    function Graph_model()
    {
        // Call the Model constructor
        parent::Model();
    }
    
	function inHour($client_id, $device, $freq)
	{
		$t1 = strtotime("now");
		$t2 = strtotime("-1 hour",$t1);
		$date1 = date("Y-m-d H:i:s",$t2);
		$date2 = date("Y-m-d H:i:s",$t1);
		
		$query = $this->db->query("select usedPercent from history where client_id = $client_id AND device = '$device' AND `datetime` > '$date1' AND `datetime` < '$date2' ");
		
		$data = $query->result();
		
		$i = 0;
		foreach($data as $row) $arr[$i++] = $row->usedPercent;
		$ans = $this->sampling($arr,$freq);
		return $ans;
	
	}
	
	function inDay($client_id, $device, $freq)
	{
		$t1 = strtotime("now");
		$t2 = strtotime("-1 day",$t1);
		$date1 = date("Y-m-d H:i:s",$t2);
		$date2 = date("Y-m-d H:i:s",$t1);
		
		$query = $this->db->query("select usedPercent from history where client_id = $client_id AND device = '$device' AND `datetime` > '$date1' AND `datetime` < '$date2'");
		
		$data = $query->result();
		
		$i = 0;
		foreach($data as $row) $arr[$i++] = $row->usedPercent;
		$ans = $this->sampling($arr,$freq);
		return $ans;
	}
	
	function inWeek($client_id, $device, $freq)
	{
		$t1 = strtotime("now");
		$t2 = strtotime("-7 day",$t1);
		$date1 = date("Y-m-d H:i:s",$t2);
		$date2 = date("Y-m-d H:i:s",$t1);
		
		$query = $this->db->query("SELECT max(usedPercent) as usedPercent FROM `history` WHERE client_id ='$client_id' AND device ='$device' AND `datetime` > '$date1' AND `datetime` < '$date2' GROUP BY hour(`datetime`),date(`datetime`) ORDER BY `datetime`");
		

		
		
		$data = $query->result();

		$i = 0;
		foreach($data as $row) $arr[$i++] = $row->usedPercent;
		$ans = $this->sampling($arr,$freq);
		return $ans;
	}
	
	function inMonth($client_id, $device, $freq)
	{
		$t1 = strtotime("now");
		$t2 = strtotime("-1 month",$t1);
		$date2 = date("Y-m-d H:i:s",$t1);
		$date1 = date("Y-m-d H:i:s",$t2);
		
		$query = $this->db->query("SELECT max(usedPercent) as usedPercent FROM `history`
				WHERE client_id = '$client_id' AND device ='$device' 
				AND `datetime` > '$date1' AND `datetime` < '$date2'
				GROUP BY hour(`datetime`),date(`datetime`)
				ORDER BY `datetime`");
		
		$data = $query->result();
		
		$i = 0;
		foreach($data as $row) $arr[$i++] = $row->usedPercent;
		$ans = $this->sampling($arr,$freq);
		return $ans;
	}
	
	private function sampling($arr,$freq){
		if (($freq >1000) || ($freq <1))
			$freq = 100 ;
		$ans = array() ;
		$numrows = sizeof($arr) ;
		$step = $numrows /$freq ;
		//echo "sampling :".$freq." : step".$step." = ".$numrows."/".$freq."<br>";
		for($i=0;$i<$freq;$i++)
		{
			$c = $i * $step ;
			$ans[$i] = $arr[floor($c)] ;
		}
		return $ans ;
	}


}



?>